/**
 * 
 */
package com.armail.client.controller.impl;

import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;

import javax.ws.rs.core.MediaType;

import com.armail.client.controller.ComposeMailController;
import com.armail.client.controller.ComposeMailControllerListener;
import com.armail.client.di.Context;
import com.armail.client.dto.Mail;
import com.armail.client.view.ComposeMailView;
import com.armail.client.view.ComposeMailViewListener;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

/**
 * @author arpit
 *
 */
public class ComposeMailControllerImpl extends ControllerImpl implements ComposeMailController, ComposeMailViewListener{

	private final Collection<ComposeMailControllerListener> listeners = new LinkedHashSet<ComposeMailControllerListener>();
	private final ComposeMailView composeMailView;
	private Mail model;
	private static final String REST_URI = "http://localhost:8080/com-armail-server/";
	private static final String SEND_MAIL = "/mails/send";
	
	@Inject
	public ComposeMailControllerImpl(Injector injector, ComposeMailView composeMailView) {
		super(injector);
		this.composeMailView = composeMailView;
		this.composeMailView.addListener(this);
	}

	@Override
	public void activate() {
		composeMailView.setModel(model);
		composeMailView.attach();
	}

	@Override
	public void deactivate() {
		composeMailView.detach();
	}

	@Override
	public void onMailSend() {
		final Mail sentMail = saveMail();
		if(sentMail != null){
			for (ComposeMailControllerListener l : listeners) {
				l.onMailSent();
			}
		}
	}
	
	private Mail saveMail() {
		ClientConfig config = new DefaultClientConfig();
		Client client = Client.create(config);
		WebResource resource = client.resource(REST_URI);

		WebResource employeeResource = resource.path("/rest/").path(SEND_MAIL);
		final ClientResponse response = employeeResource.accept(
				MediaType.APPLICATION_XML).post(ClientResponse.class, model);
		return response.getEntity(Mail.class);
	}

	@Override
	public void addListener(ComposeMailControllerListener listener) {
		this.listeners.add(listener);
	}

	@Override
	public void removeListener(ComposeMailControllerListener listener) {
		this.listeners.remove(listener);
	}

	@Override
	public void onMailSave() {
		model.setIsDraft(true);
		final Mail savedMail = saveMail();
		if (savedMail != null) {
			for (ComposeMailControllerListener l : listeners) {
				l.onMailSaved();
			}
		}}

	@Override
	public void setModel(Mail model) {
		this.model = model;
	}

}
